package com.alibaba.shopping_manager_api.security;

import com.alibaba.shopping_common.pojo.Admin;
import com.alibaba.shopping_common.pojo.Permission;
import com.alibaba.shopping_common.service.AdminService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName MyUserDetailService
 * @Description TODO
 * @Author Leo
 * @Date 2024/12/6 20:55
 */
@Service
public class MyUserDetailService implements UserDetailsService {

    @DubboReference
    private AdminService adminService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1. 认证
        Admin admin = adminService.findByAdminName(username);
        // 用户不存在
        if (admin == null || admin.getPassword() == null){
            // Security会捕获这个异常
            throw new UsernameNotFoundException("用户名不存在");
        }

        // 密码的匹配是SpringSecurity自己实现的，不需要开发者自己编写逻辑

        // 2. 授权
        // 获取用户的所有权限
        List<Permission> permissions = adminService.findAllPermission(username);
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        if (permissions.get(0) !=null){
            // 需要将自己的权限转化成Security的类型的权限才能被识别
            for (Permission permission : permissions) {
                grantedAuthorities.add(new SimpleGrantedAuthority(permission.getUrl()));
            }
        }

        // 3. 封装成UserDetail对象
        return User.withUsername(admin.getUsername())
                .password(admin.getPassword())
                .authorities(grantedAuthorities)
                .build();
    }
}




